package com.starsoft.smdc.crawler.xueqiu;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.JsonNode;
import com.starsoft.frame.fileimport.FileReader;
import com.starsoft.frame.fileimport.JsonReader;
import com.starsoft.frame.fileimport.pojo.Column;
import com.starsoft.frame.fileimport.pojo.DataTable;
import com.starsoft.frame.fileimport.pojo.NullType;
import com.starsoft.frame.fileimport.pojo.Table;
import com.starsoft.frame.fileimport.pojo.Table.TitleType;
import com.starsoft.frame.fileimport.pojo.ValueType;
import com.starsoft.frame.util.DateUtil;
import com.starsoft.frame.util.MapUtil;
import com.starsoft.frame.util.StringUtil;
import com.starsoft.smdc.bean.SmdcDiv;
import com.starsoft.smdc.bean.SmdcDivId;
import com.starsoft.smdc.bean.SmdcSecurity;
import com.starsoft.smdc.crawler.common.DivCrawler;
import com.starsoft.smdc.dao.DivDao;
import com.starsoft.smdc.util.SecurityType;

public class DivXueqiu extends XueqiuService implements DivCrawler{

	private static Logger logger = LoggerFactory.getLogger(DivXueqiu.class);
	
	@Autowired
	private DivDao divDao;
	
	private Pattern patternCash = Pattern.compile("派(.*)元");
	private Pattern patternShare = Pattern.compile("送(.*)股");
	private Pattern patternTrans = Pattern.compile("转[增]?(.*)股");

	@Override
	public List<SmdcDiv> update(SmdcSecurity security, Date beginDate) {
		return update(Arrays.asList(security), Arrays.asList(beginDate));
	}
	
	@Override
	public List<SmdcDiv> update(List<SmdcSecurity> securityList, List<Date> beginDates) {
		List<SmdcDiv> result = new ArrayList<SmdcDiv>();
		for (int i=0;i< securityList.size();i++) {
			SmdcSecurity security = securityList.get(i);
			if(SecurityType.isStock(security.getSecType())){
				result.addAll(getStockDiv(security, beginDates.get(i)));
			}
		}
		for (SmdcDiv div : result) {
			divDao.saveOrUpdate(div);
		}
		return result;
	}

	private List<SmdcDiv> getStockDiv(SmdcSecurity security, Date beginDate){
		String apiName="stockDivV5";
		String secId = convertSecId(security.getSecId(), false);
		double years = DateUtil.getYears(beginDate, new Date());
		String size =String.valueOf((int)(years*2 + 1));
		String page = "1";
		String timeStamp=String.valueOf(new Date().getTime());
		String response = this.request(apiName, secId, page, size, timeStamp);
		JsonNode responseJson = getJsonNode(response);
		JsonNode divJsonNode = responseJson.get("data").get("items");
		String divString = divJsonNode.toString();

		List<SmdcDiv> divList = new ArrayList<SmdcDiv>();
		if(StringUtil.isEmpty(response) || StringUtil.isEmpty(divString)){
			return divList;
		}
		
		List<Column> columnList = new ArrayList<Column>();
		FileReader reader=new JsonReader();

		columnList.add(new Column("dividend_year",  ValueType.String, NullType.nullable));
		columnList.add(new Column("ashare_ex_dividend_date", "divDate", ValueType.DateTime, NullType.nullable, "timestamp"));
		columnList.add(new Column("plan_explain", ValueType.String, NullType.nullable));
		
		DataTable ob= reader.read(divString, new Table(TitleType.OnlyCode,columnList));
			
		
		for (Map<String, Object> mapObject : ob.getData()) {
			try {
				Date divDate = (Date) mapObject.get("divDate");
				if (divDate==null || divDate.before(beginDate)) {
					continue;
				}
				SmdcDivId id = new SmdcDivId(security.getSecId(), divDate);
				SmdcDiv divInfo = divDao.get(id);
				if (divInfo == null) {
					divInfo = new SmdcDiv(id);
				}
				if(mapObject.get("dividend_year")!=null){
					String dividend_year = (String) mapObject.get("dividend_year");
					String earningDateStr = dividend_year.substring(0, 4);
					if(dividend_year.contains("年报")) {
						earningDateStr += "1231";
					} else {
						earningDateStr += "0630";
					}
					Date earningDate = DateUtil.toDate(earningDateStr, "yyyyMMdd");
					mapObject.put("earningDate", earningDate);
				}
				
				Date publishDate = DateUtil.bumpDate(divDate, 0, 0, -3);
				Date now = new Date();
				if(now.before(publishDate)) {
					publishDate = now;
				}
				mapObject.put("publishDate", publishDate);
				
				String plan_explain = (String) mapObject.get("plan_explain");
				Matcher matcher = patternCash.matcher(plan_explain);
				if(matcher.find()) {
					double perCashDiv = Double.parseDouble(matcher.group(1));
					mapObject.put("perCashDiv", perCashDiv/10);
				}
				matcher = patternShare.matcher(plan_explain);
				if(matcher.find()) {
					double perShareDiv = Double.parseDouble(matcher.group(1));
					mapObject.put("perShareDiv", perShareDiv/10);
				}
				matcher = patternTrans.matcher(plan_explain);
				if(matcher.find()) {
					double perShareTrans = Double.parseDouble(matcher.group(1));
					mapObject.put("perShareTrans", perShareTrans/10);
				}
				
				MapUtil.updateBean(divInfo, mapObject);
				divList.add(divInfo);
			} catch (Exception e) {
				logger.error("map to bean error " + mapObject.get("secId"), e);
			}
		}
		return divList;
	}

	@Override
	public List<SmdcDiv> update(InputStream is) {
		throw new RuntimeException("DivXueqiu not support this method");
	}
	
}
